#include "GameAudioManager.h"
#include <iostream>
#include <thread>
#include <chrono>

namespace GameEngine {

GameAudioManager& GameAudioManager::getInstance() {
    static GameAudioManager instance;
    return instance;
}

GameAudioManager::~GameAudioManager() {
    unloadAllAudio();
}

bool GameAudioManager::loadAudio(const std::string& id, const std::string& filePath) {
    if (m_audioAssets.find(id) != m_audioAssets.end()) {
        std::cout << "Audio with ID '" << id << "' already loaded." << std::endl;
        return true;
    }
    
    auto audioAsset = std::make_shared<AudioAsset>(id, filePath);
    if (audioAsset->Load()) {
        m_audioAssets[id] = audioAsset;
        std::cout << "Successfully loaded audio: " << id << std::endl;
        return true;
    } else {
        std::cout << "Failed to load audio: " << id << " from " << filePath << std::endl;
        return false;
    }
}

void GameAudioManager::unloadAudio(const std::string& id) {
    auto it = m_audioAssets.find(id);
    if (it != m_audioAssets.end()) {
        it->second->Unload();
        m_audioAssets.erase(it);
        std::cout << "Unloaded audio: " << id << std::endl;
    }
}

void GameAudioManager::unloadAllAudio() {
    for (auto& pair : m_audioAssets) {
        pair.second->Unload();
    }
    m_audioAssets.clear();
    m_currentBackgroundMusic.clear();
    std::cout << "All audio assets unloaded." << std::endl;
}

bool GameAudioManager::playBackgroundMusic(const std::string& id, bool loop) {
    auto it = m_audioAssets.find(id);
    if (it == m_audioAssets.end()) {
        std::cout << "Background music '" << id << "' not found." << std::endl;
        return false;
    }
    
    // 停止当前背景音乐
    if (!m_currentBackgroundMusic.empty() && m_currentBackgroundMusic != id) {
        stopBackgroundMusic();
    }
    
    // 设置音量和循环
    it->second->setVolume(m_backgroundMusicVolume * m_masterVolume / 100.0f);
    it->second->setLoop(loop);
    
    if (it->second->play(loop)) {
        m_currentBackgroundMusic = id;
        std::cout << "Playing background music: " << id << std::endl;
        return true;
    }
    
    return false;
}

void GameAudioManager::stopBackgroundMusic() {
    if (!m_currentBackgroundMusic.empty()) {
        auto it = m_audioAssets.find(m_currentBackgroundMusic);
        if (it != m_audioAssets.end()) {
            it->second->pause();
            it->second->restart(); // 重置到开始位置
        }
        m_currentBackgroundMusic.clear();
    }
}

void GameAudioManager::pauseBackgroundMusic() {
    if (!m_currentBackgroundMusic.empty()) {
        auto it = m_audioAssets.find(m_currentBackgroundMusic);
        if (it != m_audioAssets.end()) {
            it->second->pause();
        }
    }
}

void GameAudioManager::resumeBackgroundMusic() {
    if (!m_currentBackgroundMusic.empty()) {
        auto it = m_audioAssets.find(m_currentBackgroundMusic);
        if (it != m_audioAssets.end()) {
            it->second->play();
        }
    }
}

void GameAudioManager::setBackgroundMusicVolume(float volume) {
    m_backgroundMusicVolume = (std::max)(0.0f, (std::min)(100.0f, volume));
    
    if (!m_currentBackgroundMusic.empty()) {
        auto it = m_audioAssets.find(m_currentBackgroundMusic);
        if (it != m_audioAssets.end()) {
            it->second->setVolume(m_backgroundMusicVolume * m_masterVolume / 100.0f);
        }
    }
}

bool GameAudioManager::playSoundEffect(const std::string& id) {
    auto it = m_audioAssets.find(id);
    if (it == m_audioAssets.end()) {
        std::cout << "Sound effect '" << id << "' not found." << std::endl;
        return false;
    }
    
    // 音效通常不循环播放
    it->second->setLoop(false);
    it->second->setVolume(m_soundEffectVolume * m_masterVolume / 100.0f);
    
    return it->second->play(false);
}

void GameAudioManager::setSoundEffectVolume(float volume) {
    m_soundEffectVolume = (std::max)(0.0f, (std::min)(100.0f, volume));
}

void GameAudioManager::setMasterVolume(float volume) {
    m_masterVolume = (std::max)(0.0f, (std::min)(100.0f, volume));
    
    // 更新所有正在播放的音频的音量
    for (auto& pair : m_audioAssets) {
        if (pair.second->isPlaying()) {
            if (pair.first == m_currentBackgroundMusic) {
                pair.second->setVolume(m_backgroundMusicVolume * m_masterVolume / 100.0f);
            } else {
                pair.second->setVolume(m_soundEffectVolume * m_masterVolume / 100.0f);
            }
        }
    }
}

void GameAudioManager::muteAll(bool mute) {
    m_isMuted = mute;
    if (mute) {
        for (auto& pair : m_audioAssets) {
            pair.second->setVolume(0.0f);
        }
    } else {
        // 恢复音量
        setMasterVolume(m_masterVolume);
    }
}

void GameAudioManager::fadeInBackgroundMusic(float duration) {
    if (!m_currentBackgroundMusic.empty()) {
        auto it = m_audioAssets.find(m_currentBackgroundMusic);
        if (it != m_audioAssets.end()) {
            it->second->fadeIn(duration);
        }
    }
}

void GameAudioManager::fadeOutBackgroundMusic(float duration) {
    if (!m_currentBackgroundMusic.empty()) {
        auto it = m_audioAssets.find(m_currentBackgroundMusic);
        if (it != m_audioAssets.end()) {
            it->second->fadeOut(duration);
        }
    }
}

void GameAudioManager::switchBackgroundMusic(const std::string& newMusicId, float fadeOutDuration, float fadeInDuration) {
    // 异步处理音乐切换
    std::thread([this, newMusicId, fadeOutDuration, fadeInDuration]() {
        // 淡出当前音乐
        if (!m_currentBackgroundMusic.empty()) {
            fadeOutBackgroundMusic(fadeOutDuration);
            std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int>(fadeOutDuration * 1000)));
            stopBackgroundMusic();
        }
        
        // 淡入新音乐
        if (playBackgroundMusic(newMusicId, true)) {
            fadeInBackgroundMusic(fadeInDuration);
        }
    }).detach();
}

} // namespace GameEngine
